import numpy as np
import cv2
import os
import sys
from scipy import ndimage
import matplotlib.pyplot as plt
from datetime import datetime
import configparser


def bgsubtraction(path,filename,ext):
   print(path+filename+ext)

   bg = []
   #bg.append(cv2.bgsegm.createBackgroundSubtractorCNT())
   #bg.append(cv2.bgsegm.createBackgroundSubtractorGMG())
   bg.append(cv2.createBackgroundSubtractorKNN())
   bg.append(cv2.bgsegm.createBackgroundSubtractorMOG())
   bg.append(cv2.createBackgroundSubtractorMOG2())
   
   #method = [str(bg[0])[28:31],str(bg[1])[28:31],str(bg[2])[21:24],str(bg[3])[28:31],str(bg[4])[21:25]]
   method = [str(bg[0])[21:24],str(bg[1])[28:31],str(bg[2])[21:25]]
   
   for i in range(1,len(bg)-1):
      cap = cv2.VideoCapture(path+filename+ext)
      ret, frame = cap.read()
      total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
      fps = int(cap.get(cv2.CAP_PROP_FPS))
      print("Total number of frames in video: ",total_frames)
      print("Video frame rate: ",fps)
      print("Video length: ",np.divide(total_frames,fps)," s")
      print(i)
      out = cv2.VideoWriter(path+filename+"_subtracted_background_"+method[i]+".avi", cv2.VideoWriter_fourcc('M','J','P','G'), 100, (np.int(frame.shape[1]),np.int(frame.shape[0])),isColor=False)
      
      if ret is False:
         print("Cannot read video stream")
         sys.exit(1)
      
      fgbg = bg[i]
      
      count = 0

      while count < total_frames:
          ret, frame = cap.read()
          if ret == False:
             break
     
          fgmask = fgbg.apply(frame)
          #cv2.imshow('frame',fgmask)
          fg = cv2.copyTo(frame,fgmask)
          out.write(fgmask)
          #cv2.imshow('Foreground',fg)
          #cv2.imshow('Background',cv2.copyTo(frame,cv2.bitwise_not(fgmask)))
          k = cv2.waitKey(30) & 0xff
          if k == 27:
              break
   
          count = count + 1

      cap.release()
      out.release()
      cv2.destroyAllWindows()
      
        
      
def use_config(config,videofile): 
   folder = config['Global']['path']+config[videofile]['path']
   ext = config[videofile]['ext']
   print(folder)
   return folder,ext


def main(videofile=None):      
   # Initiate configparser:
   config = configparser.ConfigParser()
   # Set the path to the directory where this script is located:
   path = os.path.join(os.path.dirname(__file__), '')
   # Load configuration file:
   config.read(path+"config.ini")
   
   if videofile == None:
       videofile = (config['Global']['files']).split()
       for f in range(0,len(videofile)):
           (folder,ext) = use_config(config,videofile[f])
           bgsubtraction(folder,videofile[f],ext)
   else:
	   (folder,ext) = use_config(config,videofile)
	   bgsubtraction(folder,videofile,ext)
   

if __name__ == "__main__":
   start = datetime.utcnow()
   
   global videofile
   videofile = None
   
   if len(sys.argv) == 2:
	   videofile = sys.argv[1]
	   main(videofile)
   else:
       main(videofile)
   
   
   print("Start: ",start)
   print("Stop:  ",datetime.utcnow())
